<template>
  <div class="flex justify-center">
    <n-card class="w-[450px] mb-10s">
      <ClientOnly>
        <n-alert v-if="ispay" class="mb-2" title="支付成功" type="success">
          正在跳转
        </n-alert>
        <n-alert v-else-if="isTimeOut" class="mb-2" title="支付已超时" type="error">
          请刷新页面支付
        </n-alert>

        <h4 class="text-xl mb-2">微信支付</h4>
        <p class="text-sm text-gray-500 flex">距离二维码过期还剩
          <TimeBox :expire="30" class="text-rose-500" @end="handleTimeOut"/>
          ，过期后请刷新页面重新获取
        </p>

        <div class="flex justify-center py-5">
          支付总额：
          <Price :value="data.price"/>
        </div>

        <!-- 二维码组件 -->
        <QrCode v-if="data.code_url" :data="data.code_url"></QrCode>

        <div class="flex justify-center items-center py-4 text-green-500">
          <n-icon :size="35">
            <ScanCircleOutline/>
          </n-icon>

          <div class="ml-3 text-gray-500 text-sm ">
            <div>请使用微信扫一扫</div>
            <div>扫描二维码支付</div>
          </div>
        </div>
      </ClientOnly>
    </n-card>
  </div>
</template>
<script setup>
import {NAlert, NCard, NIcon} from "naive-ui";
import {ScanCircleOutline} from "@vicons/ionicons5";
import TimeBox from "~/components/TimeBox.vue";
import {useWxpayApi} from "~/apis/order.js";

const route = useRoute();

const {no} = route.query;

const {data, error} = await useWxpayApi(no);

const isTimeOut = ref(false);
const handleTimeOut = () => {
  isTimeOut.value = true;
}


// 开轮训订单状态
const ispay = ref(false);
const timer = ref(null);

function checkIspay() {
  if (timer.value) clearInterval(timer.value);
  setInterval(() => {
    useGetWxpayStatusApi(no).then((res) => {
      if (!res.error.value && res.data.value.trade_state === 'SUCCESS') {
        handleSuccess()
      }
    })
  }, 2000)
}


const handleSuccess = () => {
  ispay.value = true;
  clearInterval(timer.value);
  setInterval(() => {
    navigateTo(`/user/buy/1`, {replace: true})
  }, 2000)
}


onMounted( () => {
  if (!error.value) {
    checkIspay()
  }
})
</script>
